package redis

import (
	"context"
	"fmt"
	"github.com/gomodule/redigo/redis"
	redis1 "take-a-break/component/redis"
)

type mobileCode struct {
	client *redis1.RClient
	ctx    context.Context
	scene  string
}

func NewMobileCode(ctx context.Context, scene string) *mobileCode {
	return &mobileCode{
		client: redis1.Redis("default"),
		ctx:    ctx,
		scene:  scene,
	}
}

func getMobileCodeKeyName(scene string, mobile string) (key string) {
	return fmt.Sprintf(MobileCodeKey, scene, mobile)
}

func (c *mobileCode) SetCode(mobile, code string, ttl int) (success bool, err error) {
	key := getMobileCodeKeyName(c.scene, mobile)
	success, err = c.client.SetString(key, code, ttl)
	return
}

func (c *mobileCode) GetCode(mobile string) (code string, err error) {
	key := getMobileCodeKeyName(c.scene, mobile)
	code, err = c.client.GetString(key)
	if err != nil {
		if err.Error() == redis.ErrNil.Error() {
			err = nil
		}
	}
	return
}

func (c *mobileCode) CodeExists(mobile string) (exists bool, err error) {
	existsInt := 0
	existsInt, err = c.client.Exists(getMobileCodeKeyName(c.scene, mobile))
	if existsInt == 1 {
		exists = true
	}
	return
}

func (c *mobileCode) CodeTTL(mobile string) (ttl int, err error) {
	return c.client.TTL(getMobileCodeKeyName(c.scene, mobile))
}

func (c *mobileCode) CodeDelete(mobile string) (exists bool, err error) {
	existsInt := 0
	existsInt, err = c.client.Del(getMobileCodeKeyName(c.scene, mobile))
	if existsInt == 1 {
		exists = true
	}
	return
}
